// `dotenv` 应该列在项目的依赖项中，而不是devDependencies中
require('dotenv').config();
const fs = require('fs');
const { join } = require('path');
const { model } = require('mongoose');
const express = require('express');
const passport = require('passport');
// const LocalStrategy = require('passport-local').Strategy;

const notFoundHandler = require('./middleware/not-found');
const errorHandler = require('./middleware/error');

const models = join(__dirname, './dao/models');

const app = express();

// connect `MySQL or MongoDB`
require('./dao/mongo')();
require('./dao/sequelize').init();

fs.readdirSync(models)
  // eslint-disable-next-line
  .filter(file => ~file.search(/^[^.].*\.js$/))
  .forEach(item => require(join(models, item)));

// Bootstrap Middleware
require('./middleware/express')(app, passport);
// 注册swagger
require('./middleware/swagger-register')(app);
// 日志输出
require('./middleware/morgan-middleware')(app);

// Bootstrap Routes
require('./routes/bootstrap')(app);

/**
 * Configure Passport/Passport-Local
 */
// 通过`注册key`快速找到model
const Account = model('accounts');
// passport.use(new LocalStrategy(Account.authenticate())); // 老方法
passport.use(Account.createStrategy()); // 简化方法
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());

// catch 404 and forward to error handler
app.use(notFoundHandler);

// error handler
app.use(errorHandler);

module.exports = app;
